package com.emuporium.gymrat.server.account;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.emuporium.gymrat.server.data.User;
import com.emuporium.gymrat.server.data.UserDB;

//Shamelessly stolen from Murach's Java Servlets and JSP 2nd Edition
@SuppressWarnings("serial")
public class AccountCreateServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String email = request.getParameter("email");
		String password = request.getParameter("password");

		User user = new User(email);

		String url = null;

		if (UserDB.emailExists(email)) {
			request.setAttribute("failed",
					"Email address exists, choose another");
			request.setAttribute("redirecturl", "/account/create_account.jsp");
			url = "/includes/redirect.jsp";
		} else {
			UserDB.insert(user, password);
			request.setAttribute("redirecturl", "/home.jsp");
			url = "/includes/redirect.jsp";
		}

		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher(url);
		dispatcher.forward(request, response);

	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
}
